package master;

/**
 * 填充每个节点的下一个右侧指针II
 *
 * @author chenyw
 * @date 2022/8/6 18:50
 */

public class M117connect {
    public Node connect(Node root) {
        if (root == null) {
            return null;
        }
        Node res = root;
        while (root != null) {
            Node pre = new Node(-1);
            Node head = pre;
            while (root != null) {
                if (root.left != null && root.right != null) {
                    pre.next = root.left;
                    root.left.next = root.right;
                    pre = root.right;
                } else if (root.left == null && root.right != null) {
                    pre.next = root.right;
                    pre = root.right;
                } else if (root.right == null && root.left != null) {
                    pre.next = root.left;
                    pre = root.left;
                }
                root = root.next;
            }
            while (head != null && head.left == null && head.right == null) {
                head = head.next;
            }
            root = head;
        }
        return res;
    }
}
class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {
    }

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
}
